﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CPPEI.Coolzon.Core;
using CPPEI.Coolzon.Core.Data;
using CPPEI.Coolzon.Core.Repositories;

namespace CPPEI.Coolzon.ManagementCenter
{
    public partial class EditPrivilege : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            string Id = Request.QueryString["Id"].ToString();

            using (DbContext context = new DbContext())
            {
                IPrivilegeRepository privilegeRepository = RepositoryFactory.Create<IPrivilegeRepository>();

                CPPEI.Coolzon.Core.Data.Privilege privilege = privilegeRepository.GetPrivilege(context, new Guid(Id));
                txtId.Text = privilege.Id.ToString();
                txtCode.Text = privilege.Code;
                txtName.Text = privilege.Name;
                txtType.Text = privilege.Type;
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtCode.Text))
                {
                    lblHint.Text = "代码不能为空";
                    return;
                }
                else if (string.IsNullOrWhiteSpace(txtName.Text))
                {
                    lblHint.Text = "名称不能为空";
                    return;
                }
                else if (string.IsNullOrWhiteSpace(txtType.Text))
                {
                    lblHint.Text = "类型不能为空";
                    return;
                }
                Privilege privilege = new Privilege();
                privilege.Id = new Guid(txtId.Text);
                privilege.Code = txtCode.Text;
                privilege.Name = txtName.Text;
                privilege.Type = txtType.Text;

                using (DbContext context = new DbContext())
                {
                    IPrivilegeRepository privilegeRepository = RepositoryFactory.Create<IPrivilegeRepository>();
                    if (privilegeRepository.UpdatePrivilege(context, privilege))
                    {
                        lblHint.Text = "修改成功";
                        Response.Redirect("UserList.aspx", false);
                    }
                    else
                    {
                        lblHint.Text = "修改失败";
                    }
                }
            }
            catch (Exception ex)
            {
                lblHint.Text = "修改失败;" + ex.Message;
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("PrivilegeList.aspx", false);
        }
    }
}